<template>
  <div class="header">
    <RouterLink class="logo" to="/">
      <img src="../assets/img/logo.png" alt="logo" style="height: 60%" />
    </RouterLink>
    <div class="nav">
      <el-menu class="el-menu-demo" mode="horizontal" :default-active="currentPathIndex" @select="selectMenu">
        <el-sub-menu v-for="menu in menuData" :index="menu.url" :key="menu.id">
          <template #title>
            {{ menu.name }}
          </template>
          <el-menu-item v-for="subMenu in menu.children" :index="subMenu.url" :key="subMenu.id"
            @click="toMenu(subMenu.url)">
            {{ subMenu.name }}
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </div>
    <div class="user">
      <template v-if="userInfo">
        <el-dropdown>
          <span class="user-drop">
            <el-avatar :size="50" :src="userInfo.avatar" />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="loginOut">退出</el-dropdown-item>
              <el-dropdown-item @click="toMyOrder">我的订单</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="primary" @click="go">工作台</el-button>
      </template>
      <el-button type="primary" color="#3565D6" @click="login" v-else>登录</el-button>
    </div>
    <iframe :src="src" scrolling="auto" frameborder="0" class="iframe" id="iframe" width="100%" height="100%"
      style="position: fixed; z-index: 1000; left: 0" v-show="isShowLogin"></iframe>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { useUserStore } from "@/store/modules/user";
import { service } from "@/config/service";
import sso from "@/config/sso";
import { clearAllCookies } from "@/utils/auth";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
const router = useRouter();
const route = useRoute(); // 路由
const userStore = useUserStore();
// const isShowLogin = ref(false);
const isShowLogin = computed(() => userStore.isShowLogin);
const userInfo = computed(() => userStore.userInfo);
const allToken = computed(() => userStore.allToken);
const token = computed(() => userStore.token);
let src = "";
let system = "";
if (location.hostname.indexOf("geovisearth") != -1) {
  src = `${location.origin}/login/`;
  system = `${location.origin}/work/`;
} else if (location.hostname.indexOf("139") != -1) {
  src = `${location.origin}/login/`;
  system = `${location.origin}/work/`;
} else {
  src = `http://${location.hostname}:18082/`;
  system = `http://${location.hostname}:18081/`;
}

sso.on("auth", async (authResult) => {
  console.log("auth回调", authResult);
  // sso自动登录
  if (
    authResult.Success &&
    !token.value &&
    location.href.indexOf("quit") == -1 &&
    !isShowLogin.value
  ) {
    let { accessToken, refreshToken } = authResult.Data;
    handle(accessToken, refreshToken);
  }
  // sso未登录  清空信息
  if (!authResult.Success) {
    clearAllCookies();
    userStore.deleteUserCacheAction();
  }
});
// 退出回调
sso.on("logout", () => {
  console.log("logout回调");
  clearAllCookies();
  userStore.deleteUserCacheAction();
  // 管理系统退出到门户会带有query,清空query 防止多次调用logout
  setTimeout(() => {
    router.push({ path: "/" });
  });
});

// 退出 sso的logout不稳定，所以多次清空用户信息
const loginOut = async () => {
  clearAllCookies();
  userStore.deleteUserCacheAction();
  await service.post("/system/auth/logout");
  sso.logout();
};

// 打开控制台
const go = async () => {
  window.open(`${system}#/?ssoCheck=true`, '_blank')
};

// 获取token和用户信息
const getUserInfo = async () => {
  try {
    let res = await service.post("/ssosystem/auth/login", {
      accessToken: allToken.value.accessToken,
    });
    userStore.setTokenAction(res.data?.accessToken);
    let data = await service.get("/system/auth/get-permission-info");
    userStore.setUserInfoAction(data.data?.user);
  } catch (error) { }
};
// sso登录后处理
const handle = async (accessToken, refreshToken) => {
  // 存储token
  userStore.setAllTokenAction({ accessToken, refreshToken });
  // 登录子系统
  sso.login(accessToken);
  // 获取token和用户信息
  getUserInfo();
  userStore.setisShowLogin(false);
  // isShowLogin.value = false;
};

// 登录
const login = () => {
  userStore.setisShowLogin(true);
  // isShowLogin.value = true;
};

const currentPathIndex = ref("");
watch(
  () => router.currentRoute.value.path,
  (toPath) => {
    if (route.path) {
      currentPathIndex.value = toPath.replace("/", "");
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

const info = () => {
  ElMessage("此功能即将开放，敬请期待");
};

//跳转用户手册
const tohelp = () => {
  window.open("https://www.yuque.com/zhaozhe-igbt8/uead03/gc95rrgu1fdbuhgy");
};

const menuData = ref([]);
const getMenu = async () => {
  let data = await service.get("/solutionManage/getMenuAddresses");
  menuData.value = data.data;
};
const toMenu = (path) => {
  if (path === "null") {
    info();
  } else if (path === "help") {
    tohelp();
  } else if (path === "apitest" || path === "testmanage") {
    if (userInfo.value) {
      if (path === "apitest") {
        window.open(`${system}#/apiManage/debug?ssoCheck=true`, '_blank')
      } else if (path === "testmanage") {
        window.open(`${system}#/test/demandManage?ssoCheck=true`, '_blank')
      }
    } else {
      ElMessage({ message: "请先进行用户登录！", type: "warning" });
      userStore.setisShowLogin(true);
      // isShowLogin.value = true;
    }
    return;
  } else {
    router.push({ name: path });
  }
};
const selectMenu = () => { }
const toMyOrder = () => {
  window.open(`${system}#/order/myOrder?ssoCheck=true`, '_blank')
}
onMounted(() => {
  getMenu();
  clearAllCookies();
  window.addEventListener("message", async (e) => {
    let data = e.data;
    let title = data.title;
    console.log(title, data);
    if (title == "loginResult") {
      const accessToken = data.data.Data.accessToken;
      const refreshToken = data.data.Data.refreshToken;
      handle(accessToken, refreshToken);
    } else if (title == "wechatLoginResult") {
      const accessToken = data.data.Data.loginResult.accessToken;
      const refreshToken = data.data.Data.loginResult.refreshToken;
      handle(accessToken, refreshToken);
    } else if (title == "appLoginResult") {
      const accessToken = data.data.Data.accessToken;
      handle(accessToken, "");
    } else if (title == "close") {
      userStore.setisShowLogin(false);
      // isShowLogin.value = false;
    }
  });
});
</script>

<style lang="scss">
.header {
  width: 100%;
  height: 60px;
  display: flex;
  background-color: rgba(50, 64, 87, 1);
  position: fixed;
  top: 0;
  z-index: 5;
  padding: 0 12%;

  .logo {
    height: 100%;
    width: 10%;
    display: flex;
    align-items: center;
  }

  .logo span {
    font-size: 20px;
    font-weight: 600;
    color: #fff;
  }

  .nav {
    padding-left: 10%;
    width: 50%;
  }

  .user {
    padding: 15px;
    cursor: pointer;
    display: flex;
    align-items: center;

    &-drop {
      display: flex;
      align-items: center;
      color: #fff;
      outline: none;

      span {
        margin-right: 10px;
      }
    }
  }
}
</style>
<style lang="scss" scope>
.header {
  .el-menu {
    background-color: transparent !important;
  }

  .el-sub-menu__title {
    color: #fff !important;
  }

  .el-menu--horizontal>.el-sub-menu .el-sub-menu__title:hover {
    background-color: #455878a8 !important;
  }
}
</style>
